<template>
  <div class="w-[100%] h-[100%]">

    <div class="mt-[0px]">
      <ContentWrap>
        <SearchBox :queryForm="searchList" :showExpland="true" @query="handleSearchQuery"
                   :show-len="3"
                   :show-export="false"/>
      </ContentWrap>
    </div>

    <div class="mt-[30px]">
      <el-button type="primary" color="#3721FF" round @click="handleBtnClick({ type:'add' })">+
        新增网站模板
      </el-button>
      <el-button type="primary" color="rgba(55,33,255,0.08)"
                 @click="handleBtnClick({ type:'importArea' })" style="color:#3721FF" round>批量导入
      </el-button>
    </div>

    <div class="mt-[30px]">
      <QueryTable
        pk="id"
        :list="dataList"
        :total="total"
        :btns="tableBtnList"
        @execute="handleBtnClick"
        v-model="queryParams"
        :thead="th"
        :show-action="true"
        :show-expand="false"
      >
        <template #previewPicUrls="{row}">
          <ImagePreview :src="row.previewPicUrls" :width="50" :height="50"/>
        </template>

        <template #status="{row,index}">
          <div class="relative">
            <el-switch
              v-model="row.status"
              class="ml-2"
              :active-value="0"
              :inactive-value="1"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            />

            <div class="absolute top-[0] left-[0] w-[100%] h-[100%]"
                 @click="handleBtnClick({
                 type:'switchStatus',
                 row,index
                 })"

            ></div>
          </div>

        </template>
      </QueryTable>

    </div>

    <ComfirmPops ref="ConfirmPropsRef" :type="'radio'" @confirm="getConfirmValue" :title="selectedRow.id ?`编辑` : `新增`"
                 :show-icon="false" width="537">
      <template #content>
        <InfoAction ref="InfoActionRef" :info="selectedRow"/>
      </template>
    </ComfirmPops>
  </div>
</template>
<script setup lang="ts">
import Icon from "@/components/Icon/src/Icon.vue"
import QueryTable from "@/components/TableData/index.vue"
import ImagePreview from "@/components/ImagePreview/index.vue"
import InfoAction from "./components/InfoAction.vue"
import type {TradeOrderQueryVO} from "@/api/mall/trade/order";
import {DICT_TYPE, getIntDictOptions, getStrDictOptions} from "@/utils/dict";
import type {PurchaseAdvice} from "@/api/purchase/advice/type";
import {throttle, confirmPromote} from "@/utils";
import {useRoute} from "vue-router";
import {useMessage} from "@/hooks/web/useMessage";

import {WebDiyTemplateApi} from "@/api/template/index"

const portType = getStrDictOptions(DICT_TYPE.FIT_PORT)


const route = useRoute();

const message = useMessage();

const InfoActionRef = ref(null)
const ConfirmPropsRef = ref(null)

const searchList: TradeOrderQueryVO[] = ref(
  [
    {
      label: '模版名称',
      code: 'name',
      type: 'input',
    },
    {
      label: '适用端口',
      code: 'applicablePorts',
      type: 'select',
      options:portType
    },

  ]
)
const initQueryParams = {
  pageNo: 1, pageSize: 10
}

const tableBtnList = ref([
  {
    color: '#3721FF',
    code: 'preview',
    name: '预览'
  },

  {
    color: '#3721FF',
    code: 'edit',
    name: '编辑'
  },

  {
    color: '#FF4E00',
    code: 'delItem',
    name: '删除'
  }
]);


const th = ref( route.query?.type == 1 ?
  [
  {
    name: '模板缩略图',
    code: 'previewPicUrls',
    required: true
  },
  {
    name: '模板名称',
    code: 'name',
    required: true
  },
  {
    name: '适用端口',
    code: 'applicablePorts',
    required: true
  },
  {
    name: '是否开启',
    code: 'status',
    required: true
  },

  {
    name: '创建者',
    code: 'creatorNickname',
  },
  {
    name: '创建时间',
    code: 'createTime',
    date: true
  },

]
  :
  [
    {
      name: '模板缩略图',
      code: 'previewPicUrls',
      required: true
    },
    {
      name: '模板名称',
      code: 'name',
      required: true
    },
    {
      name: '落地页形态',
      code: 'landingPageForm',
      required: true
    },
    {
      name: '营销功能',
      code: 'marketingFeatures',
      required: true
    },
    {
      name: '推荐场景',
      code: 'recommendedScenario',
      required: true
    },
    {
      name: '适用端口',
      code: 'applicablePorts',
      required: true
    },
    {
      name: '是否开启',
      code: 'status',
      required: true
    },

    {
      name: '创建者',
      code: 'creatorNickname',
    },
    {
      name: '创建时间',
      code: 'createTime',
      date: true
    },

  ]

);

const dataList = ref<GlobeStateDetailVO[]>([]);
const ids = ref<Array<string | number>>([]);
const total = ref(0);

const initRow = {}

const selectedRow = ref<PurchaseAdvice>({...initRow})

const isShowDialog = ref(false)


const queryParams = ref({
  ...initQueryParams
})

const handleSearchQuery = (val) => {
  /***
   * 搜索框查询条件，目前考虑在查询时 queryParams = {...val,pageNo:1,pageSize:10}
   * */
  queryParams.value = {
    ...initQueryParams,
    ...val
  }
  getList();
}

const handleBtnClick = e => {
  let type = e.type;
  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不存在`)
  }
}

const fn = {
  add() {
    selectedRow.value = {}
    ConfirmPropsRef.value && ConfirmPropsRef.value.show();
  },
  edit({data}) {
    selectedRow.value = {
      ...data.row,
      applicablePorts: data.row.applicablePorts &&  data.row.applicablePorts.split(','),
      marketingFeatures:data.row.marketingFeatures &&  data.row.marketingFeatures.split(','),
    }
    ConfirmPropsRef.value && ConfirmPropsRef.value.show();
  },
  preview({data}) {
    window.open(data.row.previewPicUrls)
  },
  delItem: throttle(async ({data}) => {
    await confirmPromote({
      content: "确认删除数据吗？"
    })

    await WebDiyTemplateApi.deleteWebDiyTemplate(data.row.id);
    getList();

  }, 1000),
  importArea() {
    //TODO 批量导入
  },
  pagination() {
    getList();
  },
  switchStatus: throttle(async ({row, index}) => {
    try {
      await confirmPromote({
        content: `确认${row.status == 1 ? '开启' : '关闭'}吗？`
      })

      let option = {
        id: row.id,
        status: row.status == 0 ? 1 : 0
      }

      await WebDiyTemplateApi.switchStatus(option)
      row.status = option.status

    } catch (e) {
    }

  }, 1000)

}


const getConfirmValue = async () => {
  InfoActionRef.value && await InfoActionRef.value.confirm(() => {
    // 刷新列表
    getList();
    message.success('操作成功');
    ConfirmPropsRef.value && ConfirmPropsRef.value.hide();
  });

}


const getList = async () => {
  let res = await WebDiyTemplateApi.getWebDiyTemplatePage({
    ...queryParams.value,
    type: route.query?.type
  });
  dataList.value = res.list;
  total.value = res.total;
}


onMounted(() => {
  getList();

})

</script>
<style lang="scss" scoped>

</style>
